package com.heima.comment.service.impl;

import com.heima.comment.dto.CommentDto;
import com.heima.comment.dto.CommentLikeDto;
import com.heima.comment.entity.ApCommentLike;
import com.heima.comment.vo.ApCommentVo;
import com.heima.common.aliyun.GreenTextScan;
import com.heima.common.dto.ResponseResult;
import com.heima.common.entity.User;
import com.heima.common.enums.AppHttpCodeEnum;
import com.heima.common.util.AppThreadLocal;
import com.heima.comment.client.UserClient;
import com.heima.comment.dto.CommentSaveDto;
import com.heima.comment.entity.ApComment;
import com.heima.comment.entity.ApUser;
import com.heima.comment.service.ICommentService;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.PageRequest;
import org.springframework.data.domain.Pageable;
import org.springframework.data.domain.Sort;
import org.springframework.data.mongodb.core.MongoTemplate;
import org.springframework.data.mongodb.core.query.Criteria;
import org.springframework.data.mongodb.core.query.Query;
import org.springframework.data.mongodb.core.query.Update;
import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;

import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.Map;

@Service
public class CommentServiceImpl implements ICommentService {
    @Autowired
    private GreenTextScan textScan;
    @Autowired
    private UserClient userClient;
    @Autowired
    private MongoTemplate template;
    /**
     * 评论添加
     * @param dto
     * @return
     */
    @Override
    public ResponseResult commentSave(CommentSaveDto dto) {
//        评论内容判断
        if (dto == null || StringUtils.isEmpty(dto.getContent() )|| dto.getContent().length() > 140){
            return ResponseResult.errorResult(AppHttpCodeEnum.PARAM_INVALID);
        }
//        判断是否登录
        User user = AppThreadLocal.get();
        if (user == null){
            return ResponseResult.errorResult(AppHttpCodeEnum.PARAM_INVALID);
        }
//        集成阿里云审核
//        审核文本
        try {
            Map map = textScan.greenTextScan(dto.getContent());
            Object suggestion = map.get("suggestion");
            if (!suggestion.equals("pass")){
                return ResponseResult.errorResult(AppHttpCodeEnum.PARAM_INVALID);
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
//        安全过滤
        ApComment apComment = new ApComment();
        apComment.setAuthorId(user.getUserId());
//        存入authorId和image
//        1.存入网关，这个方法可行但麻烦
//        2.根据id查询，这个好（耦合性低） 远程调用
        ResponseResult<ApUser> responseResult = userClient.getById(user.getUserId());
        if (responseResult.getCode().equals(AppHttpCodeEnum.SUCCESS.getCode())){
            ApUser apUser = responseResult.getData();
            apComment.setAuthorName(apUser.getName());
            apComment.setImage(apUser.getImage());
        }
        apComment.setEntryId(dto.getArticleId());
        apComment.setType(0);
        apComment.setContent(dto.getContent());
        apComment.setLikes(0);
        apComment.setReply(0);
        apComment.setFlag(0);
        apComment.setCreatedTime(new Date());



//        保存评论
        template.save(apComment);
        return ResponseResult.okResult();
    }


    /**
     * 评论点赞
     * @param dto
     * @return
     */
    @Override
    public ResponseResult like(CommentLikeDto dto) {
//        根据评论id进行点赞
        ApCommentLike apCommentLike = new ApCommentLike();
        apCommentLike.setCommentId(dto.getCommentId());
        Integer operation = dto.getOperation();
        apCommentLike.setOperation(operation);
//        判断是否登录
        User user = AppThreadLocal.get();
        if (user == null){
            return ResponseResult.errorResult(AppHttpCodeEnum.PARAM_INVALID);
        }
        apCommentLike.setAuthorId(user.getUserId());
//        判断是否点赞
        Query query = new Query();
        query.addCriteria(Criteria.where("authorId").is(user.getUserId()));
        query.addCriteria(Criteria.where("commentId").is(dto.getCommentId()));
        ApCommentLike one = template.findOne(query, ApCommentLike.class);
//        没点赞
        int count = 0;
        if (one == null){
            if (dto.getOperation() == 0){
                template.save(apCommentLike);
                count = 1;
            }
        }else {
//            点赞了，如果是重复操作不管
//            如果是不同操作，进行修改
            if (operation != one.getOperation()){
                one.setOperation(operation);
                template.save(one);
                if (operation == 0){
                    count = 1;
                }else {
                    count = -1;
                }
            }


        }

        if (count != 0){
            Query query1 = new Query();
            query1.addCriteria(Criteria.where("id").is(user.getUserId()));

            Update update = new Update();
            update.inc("likes",count);
            template.updateFirst(query1,update,ApCommentLike.class);
        }
        return ResponseResult.okResult();


    }

    /**
     * 评论列表分页查询
     * @param dto
     * @return
     */
    @Override
    public ResponseResult load(CommentDto dto) {
        Query query = new Query();
//        根据id查询用户
        query.addCriteria(Criteria.where("entryId").is(dto.getArticleId()));
//       查询时间
        query.addCriteria(Criteria.where("createdTime").lt(dto.getMinDate()));
//        分页查询
        Pageable page = PageRequest.of(0,10,Sort.Direction.DESC,"createdTime");
        query.with(page);
        List<ApComment> apComments = template.find(query, ApComment.class);

        List<String> commentId = new ArrayList<>();
        List<ApCommentVo> vos = new ArrayList<>();
        for (ApComment apComment : apComments) {
            ApCommentVo vo = new ApCommentVo();
            BeanUtils.copyProperties(apComment,vo);
            vo.setOperation(1);
            vos.add(vo);

            commentId.add(apComment.getId());
        }

//        判断是否登录
        User user = AppThreadLocal.get();
        if (user == null){
            return ResponseResult.okResult();
        }

//        存在用户  查询
        Query likeQuery = new Query();
        likeQuery.addCriteria(Criteria.where("authorId").is(user.getUserId()));
        likeQuery.addCriteria(Criteria.where("commentId").in(commentId));
        List<ApCommentLike> apCommentLikes = template.find(likeQuery, ApCommentLike.class);
        List<String> likeIds = new ArrayList<>();
        for (ApCommentLike apCommentLike : apCommentLikes) {
            if (apCommentLike.getOperation() == 0){
                likeIds.add(apCommentLike.getCommentId());
            }
        }

        for (ApCommentVo vo : vos) {
            if (likeIds.contains(vo.getId())){
                vo.setOperation(0);
            }
        }

        return ResponseResult.okResult(vos);
    }
}
